package com.nowcoder.community.controller.interceptor;

import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.DataService;
import com.nowcoder.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName DataInterceptor
 * @Description
 * @Author hhwu
 * @Date 2022/6/1 15:03
 * Version 1.0
 **/

@Component
public class DataInterceptor implements HandlerInterceptor {
    /**
     * @Author hhwu
     * @Description //TODO 记录uv和DAU
     * @Date 15:04 2022/6/1
     **/

    @Autowired
    private DataService dataService;

    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * @Author hhwu
         * @Description //TODO 用户或游客只要尝试访问controller，就是活跃的
         * @Date 15:05 2022/6/1
         * @Param [request, response, handler]
         * @return boolean
         **/
        // 统计UV
        String ip = request.getRemoteHost();
        dataService.recordUV(ip);

        // 统计DAU
        User user = hostHolder.getUser();
        if (user != null) {
            dataService.recordDAU(user.getId());
        }

        return true;// 该方法只是加塞统计，然后直接放行
    }
}
